package work.timejay.user.service.users.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import work.timejay.common.SuperServiceImpl;
import work.timejay.dto.UserEditDTO;
import work.timejay.dto.UserRegisterDTO;
import work.timejay.entity.User;
import work.timejay.enums.UserEnums;
import work.timejay.exception.TimeJayException;
import work.timejay.mapper.UserMapper;
import work.timejay.user.entity.books.UserBookType;
import work.timejay.user.service.books.UserBookTypeService;
import work.timejay.user.service.users.UserService;
import work.timejay.utils.FileUtils;
import work.timejay.utils.LoginHelper;

import javax.swing.text.TabExpander;

/**
 * @className:UserServiceImpl.java
 * @author:王文杰
 * @version:1.0.0
 * @description:用户业务层
 * @createTime 2023年11月23日 11:04:00
 */
@Service
public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserBookTypeService userBookTypeService;

    @Autowired
    private FileUtils fileUtils;

    @Override
    public User saveUserInfo(UserRegisterDTO dto) {
        User bean = lambdaQuery()
                .eq(User::getPhone, dto.getPhone())
                .one();
        if (null != bean) {
            throw TimeJayException.fail("500", "注册失败，账户已经存在");
        }
        User user = User.createEntityByRegister(dto);
        save(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editUserInfo(UserEditDTO dto) {
        User loginUserInfo = LoginHelper.loginUserInfo();
        User user = BeanUtil.toBean(dto, User.class);
        user.setId(loginUserInfo.getId());
        user.setInitStatus(UserEnums.InitStatus.INIT_SUCCESS.getCode());
        updateById(user);
        //类目不为空更新
        if (CollectionUtils.isNotEmpty(dto.getLikeType())) {
            userBookTypeService.saveUserBookInfoByUserId(dto.getLikeType(), loginUserInfo.getId());
        }

    }

    @Override
    public User findUserById(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public User getUserInfo() {
        User user = LoginHelper.loginUserInfo();
//        if (StringUtils.isNotBlank(user.getLogoPath()) && !user.getLogoPath().contains("http")) {
//            user.setLogoPath(fileUtils.preview(user.getLogoPath()));
//        }
        return user;
    }
}
